import { observable, computed } from 'mobx';
import { getAds, createAds, updateAds } from './AdsHttpResource';
import { notEmpty, isUrl } from '../../../service/Validator';
import { ItemModel, IItemProps, Validate } from '../../ItemModel';

export interface IAdsModel extends IItemProps {
    name: string;
    items: IAd[];
}

export interface IAd {
    url: string;
    imageUrl: string;
}

export class AdsModel extends ItemModel<IAdsModel> {

    @observable data = {
        name: "",
        items: [
            { url: "", imageUrl: "" },
            { url: "", imageUrl: "" },
            { url: "", imageUrl: "" },
            { url: "", imageUrl: "" }
        ]
    }

    @Validate(`请输入广告位名称`)
    @computed get nameValid() {
        return notEmpty(this.data.name);
    }

    @Validate(`请输入合法的广告位链接`)
    @computed get adsUrlValid() { return this.data.items.every(ad => isUrl(ad.url)) }

    @Validate(`请上传广告位图片`)
    @computed get adsImgValid() { return this.data.items.every(ad => notEmpty(ad.imageUrl)) }

    fetchItemImpl(id: string) {
        return getAds(id);
    }

    updateItemImpl(id: string, data: IAdsModel) {
        return updateAds(id, data);
    }

    createItemImpl(data: IAdsModel) {
        return createAds(data);
    }
}
